package org.sbear.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.sbear.pojo.RpcRequest;
import org.sbear.service.UserServiceImpl;
import org.sbear.util.ApplicationContextUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class UserServiceHandler extends SimpleChannelInboundHandler<RpcRequest>{
    /**
     * 当客户端读取数据时,该方法会被调用
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        this.channelRead0(ctx, (RpcRequest) msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcRequest rpcRequest) throws Exception {
        ApplicationContext applicationContext = ApplicationContextUtil.getApplicationContext();
        System.out.println(applicationContext);
        //获取类名
        String className = rpcRequest.getClassName();
        System.out.println(className);
        //通过applicationContext获取service实现类
        Object serviceBean = applicationContext.getBean(className);
        //获取入参，并通过class.getMethod方法找到需要实际执行的方法
        Method method = serviceBean.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        //进行执行，写入返回结果
        channelHandlerContext.writeAndFlush(method.invoke(serviceBean, rpcRequest.getParameters()));
    }
}


